package com.starbaba.loanActivity.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.jumai.server.qiniu.QiniuUploadUtils;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.loanActivity.model.LoanProductModel;
import com.starbaba.loanActivity.model.TagtypeModel;
import com.starbaba.loanActivity.service.LoanProductService;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.JSONUtils;

/**
 * 贷款产品管理
 * @version 1.0
 */
@Component
@SuppressWarnings("rawtypes") 
public class LoanProductServiceImpl implements LoanProductService {
    
	@SuppressWarnings("deprecation")
    private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
	
    @Override
	public List<LoanProductModel> getDataList(int iDisplayStart, int iDisplayLength, PageResponse pageResponse, Map<String, Object> paramsMap) {
        
        String activityid = (String) paramsMap.get("activityid");
		String status = (String) paramsMap.get("status");
		String name = (String) paramsMap.get("name");

		String sql = "select c.id,c.name,c.summary,c.tag,c.url,"
		        + "c.logo,c.status,"
		        + "DATE_FORMAT(c.utime, '%Y-%m-%d %H:%i:%s') AS utime,"
		        + "c.ratetype,c.rate,c.ctime,c.operator,c.type,c.position,c.remark "
		        + "from loan_product_info c "
		        + "where 1=1 ";
		
		String selectSql = "";
		if (!StringUtils.isEmpty(activityid)) {
            selectSql += " and c.id = " + activityid ;
        }
		if (!StringUtils.isEmpty(name)) {
			selectSql += " and c.name like '%" +name + "%'";
		}
		if (!StringUtils.isEmpty(status)) {
            selectSql += " and c.status = '" + status + "'";
        }

		sql += selectSql;
		sql += " order by c.position asc limit " + iDisplayStart + " , " + iDisplayLength;

		String countSql = "select count(1) from loan_product_info c where 1=1 " + selectSql;
		List<LoanProductModel> list = null;
		try {
			int count = dao.getInt(countSql);
			list = dao.list(sql, LoanProductModel.class, new Object[] {});
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		} catch (AppException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public Long save(Map<String, Object> paramsMap, LoanProductModel bean) {

		String countsql = "select position+1 from loan_product_info ";
		
		LoanProductModel model = setValue(bean);
		
		SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = tempFormat.format(new Date());
        model.setCtime(date);
        
		int position = 0;
		try {
			position = dao.getInt(countsql, new Object[] {});
			model.setPosition(position);
			Long id = dao.addReturnGeneratedKey(model);
			return id;
		} catch (AppException e) {
			e.printStackTrace();
			return 0L;
		}
	}

	public LoanProductModel setValue(LoanProductModel bean) {

		LoanProductModel model = null;
		try {
			model = new LoanProductModel();
			String thumbnail = null;
			File thumbnailFile = bean.getImg();
			if (thumbnailFile != null) {
				thumbnail = uploadToQiniu(thumbnailFile);
				model.setLogo(thumbnail);
			}
			String market_img = null;
			File marketFile = bean.getMarket_img();
			if (marketFile != null) {
				market_img = uploadToQiniu(marketFile);
				model.setMarket_tag(market_img);
			}
			if (!StringUtils.isEmpty(bean.getSummary())){
				model.setSummary(bean.getSummary());
			}
			if (!StringUtils.isEmpty(bean.getName())){
				model.setName(bean.getName());
			}
			if (!StringUtils.isEmpty(bean.getUrl())){
				model.setUrl(bean.getUrl());
			}
			if (!StringUtils.isEmpty(bean.getFlow_text())){							
				model.setFlow_text(bean.getFlow_text());
			}
			if (!StringUtils.isEmpty(bean.getFlow_pic())){
				model.setFlow_pic(bean.getFlow_pic());			
			}
			if (!StringUtils.isEmpty(bean.getRate())){
				model.setRate(bean.getRate());			
			}
							
			if (!StringUtils.isEmpty(bean.getLenddate())){
				model.setLenddate(bean.getLenddate());					
			}
			if (!StringUtils.isEmpty(bean.getLoanlimit())){
				model.setLoanlimit(bean.getLoanlimit());					
			}	
			if (!StringUtils.isEmpty(bean.getApply_condition())){			
				model.setApply_condition(bean.getApply_condition());
			}
			if (!StringUtils.isEmpty(bean.getIntroduction())){		
				model.setIntroduction(bean.getIntroduction());
			}
			if (!StringUtils.isEmpty(bean.getModelid())){			
				model.setModelid(bean.getModelid());
			}
			if (!StringUtils.isEmpty(bean.getAdvantage())){			
				model.setAdvantage(bean.getAdvantage());
			}
			if (!StringUtils.isEmpty(bean.getOperator())){			
				model.setOperator(bean.getOperator());
			}
			if(bean.getStatus() != null){
				model.setStatus(bean.getStatus());
			}
			if(bean.getApi() == null){
			    model.setApi(0);
			}else{
				model.setApi(bean.getApi());
			}
			if(bean.getUnion_type() == null){
			    model.setUnion_type(0);
			}else{
				model.setUnion_type(bean.getUnion_type());
			}
			if(bean.getInfo_type() != null){
				model.setInfo_type(bean.getInfo_type());
			}
			if(bean.getApi_model_id() != null){
				model.setApi_model_id(bean.getApi_model_id());
			}
			if(!StringUtils.isEmpty(bean.getRemark())){
			    model.setRemark(bean.getRemark());
			}
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = format.format(new Date());
            model.setUtime(date);
            model.setOperator(bean.getOperator());
			model.setTag(bean.getModelid());
			model.setRatetype(bean.getRatetype());
			
			TagtypeModel t_model = new TagtypeModel();
			if(!StringUtils.isEmpty(bean.getIdentity_type())){
				String[] identity_types = bean.getIdentity_type().split(",");
				t_model.setIdentity(identity_types);
			}
			if(!StringUtils.isEmpty(bean.getCredit_type())){
				String[] credit_types = bean.getCredit_type().split(",");
				t_model.setCredit(credit_types);
			}
			if(!StringUtils.isEmpty(bean.getCash_loan_type())){
				String[] cash_loan_types = bean.getCash_loan_type().split(",");
				t_model.setCash_loan(cash_loan_types);
			}
			model.setType(JSONUtils.toJsonString(t_model));	
			model.setMinlimit(bean.getMinlimit());
			model.setMaxlimit(bean.getMaxlimit());						
			model.setPosition(bean.getPosition());
			model.setInitcount(bean.getInitcount());
			model.setMinterm(bean.getMinterm());
			model.setMaxterm(bean.getMaxterm());
			model.setSuccess_count(bean.getSuccess_count());
			model.setHeat(bean.getHeat());
			model.setPass_rate(bean.getPass_rate());
			model.setLoan_speed(bean.getLoan_speed());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return model;
	}

	public String uploadToQiniu(File srcFile) {
		String iconUrl = null;
		if (srcFile.isDirectory()) {
			return iconUrl;
		} else {
			try {
				FileInputStream in = new FileInputStream(srcFile);
				// Zone为七牛机房所在地，根据源所在机房配置
		        Configuration config = new Configuration(Zone.zone0()); 
				iconUrl = QiniuUploadUtils.updateImg("loan", in, null, config);
		        in.close();
			} catch (Exception e) {
				e.printStackTrace();
				LogService.error(e);
			}
		}
		return iconUrl;
	}

	@Override
	public void update(Map<String, Object> paramsMap, LoanProductModel bean) {
		
		LoanProductModel model = setValue(bean);
		model.setId(bean.getId());
		try {
			String temp = "select id,logo,ctime from loan.loan_product_info where id = ?";
			LoanProductModel tempModel = dao.get(temp, LoanProductModel.class, model.getId());
			if (StringUtils.isEmpty(model.getLogo()))
				model.setLogo(tempModel.getLogo());
			if (StringUtils.isEmpty(model.getCtime())){
				model.setCtime(tempModel.getCtime());
			}
			model.setId(tempModel.getId());
//			StringBuffer strSql = new StringBuffer();
//			strSql.append("delete from loan.loan_product_info where id = ?");
//			int result = dao.update(model, (String[]) new Object[]{model.getId()});
			dao.update(model, new String[]{"id"});
//			if(result > 0 ){
//				dao.add(model);
//			}
		} catch (Exception e) {
			e.printStackTrace();
			LogService.error(e);
		}
	}
	
	/**
	 * 查询所有产品
	 * @param pageResponse
	 * @param paramsMap
	 * @return
	 */
	@Override
	public List<LoanProductModel> getAllList(PageResponse pageResponse) {

		String sql = "select c.id,c.name,c.summary,c.tag,c.url," + "c.logo,c.status," + "DATE_FORMAT(c.utime, '%Y-%m-%d %H:%i:%s') AS utime,"
				+ "c.ratetype,c.rate,c.ctime,c.operator,c.type,c.position " + "from loan_product_info c ";

		List<LoanProductModel> list = null;
		try {
			list = dao.list(sql, LoanProductModel.class, new Object[] {});
		} catch (AppException e) {
			e.printStackTrace();
		}
		return list;
	}
}
